package com.sara.service.impl;

import com.github.pagehelper.Constant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sara.entity.*;
import com.sara.exception.ServiceException;
import com.sara.mapper.OrderEmployeeMapper;
import com.sara.mapper.OrderMapper;
import com.sara.mapper.OrderPartsMapper;
import com.sara.mapper.ServiceTypeMapper;
import com.sara.service.OrderService;
import com.sara.vo.OrderInfoVo;
import com.sara.vo.OrderVo;
import com.sara.vo.PartsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @author Wayne
 * @date 2019/1/11
 */

@Service
public class OrderServiceImpl implements OrderService {
     private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Autowired
    private ServiceTypeMapper serviceTypeMapper;

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderEmployeeMapper orderEmployeeMapper;

    @Autowired
    private OrderPartsMapper orderPartsMapper;
    /**
     * @return 所有的服务类型
     */
    @Override
    public List<ServiceType> findAllServiceType() {
        ServiceTypeExample serviceTypeExample = new ServiceTypeExample();
        serviceTypeExample.createCriteria();
        return serviceTypeMapper.selectByExample(serviceTypeExample);

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveOrder(OrderVo orderVo, Integer employeeId) {
        Order order = new Order();
        order.setCarId(orderVo.getCarId());
        order.setOrderMoney(orderVo.getFee());
        order.setServiceTypeId(orderVo.getServiceTypeId());
        order.setState(Order.ORDER_STATE_NEW);

        System.out.println("ordermoney" + orderVo.getFee());
        System.out.println("ServiceTypeId" + orderVo.getServiceTypeId());
        orderMapper.insertSelective(order);

        // 新增员工订单关系表
        saveEmployeeOrder(order.getId(),employeeId);


        // 新增配件订单关系表
        List<PartsVo> partsVoList = orderVo.getPartsLists();
        addOrderParts(order.getId(), partsVoList );
        logger.info("{}--新增订单{}", employeeId, order.getId());

    }

    /**
     * 根据条件去查询订单
     *
     * @param queryMap 条件集合queryMap
     * @return 订单分页
     */
    @Override
    public PageInfo<Order> findPageByParam(Map<String, Object> queryMap) {
        PageHelper.startPage(Integer.parseInt(String.valueOf(queryMap.get("pageNo"))), com.sara.util.Constant.DEFAULT_PAGE_SIZE);
        List<Order> orderList = orderMapper.findUndonePageByParam(queryMap);
        PageInfo<Order> pageInfo = new PageInfo<>(orderList);
        return pageInfo;

    }

    @Override
    public Order findOrderById(Integer id) {
        return orderMapper.findWithCarInfoById(id);
    }

    @Override
    public ServiceType findServiceTypeById(Integer serviceTypeId) {

        return serviceTypeMapper.selectByPrimaryKey(serviceTypeId);
    }

    @Override
    public Map<String, Object> findEditByOrderId(Integer id) {
        return orderMapper.selectByEditId(id);
    }

    /**
     * 更新订单数据，修改订单
     *
     * @param orderVo
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void editOrder(OrderVo orderVo) {
        //先更新订单，从ordervo的order id 去查出来order信息，然后此次跟新关系
        Order order = orderMapper.selectByPrimaryKey(orderVo.getId());
        order.setCarId(orderVo.getCarId());
        order.setOrderMoney(orderVo.getFee());
        order.setServiceTypeId(orderVo.getServiceTypeId());
        orderMapper.updateByPrimaryKeySelective(order);

        // 删除order跟parts零件的关联关系，然后重新建立关联关系

        OrderPartsExample orderPartsExample = new OrderPartsExample();
        orderPartsExample.createCriteria().andOrderIdEqualTo(orderVo.getId());

        //
        orderPartsMapper.deleteByExample(orderPartsExample);
        //

        List<PartsVo> partsLists = orderVo.getPartsLists();
        addOrderParts(orderVo.getId(), partsLists);
        logger.info("更新订单{}", order.getId());
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteOrder(Integer id) {
        OrderPartsExample orderPartsExample = new OrderPartsExample();
        orderPartsExample.createCriteria().andOrderIdEqualTo(id);
        orderPartsMapper.deleteByExample(orderPartsExample);


        OrderEmployeeExample orderEmployeeExample = new OrderEmployeeExample();
        orderEmployeeExample.createCriteria().andOrderIdEqualTo(id);
        orderEmployeeMapper.deleteByExample(orderEmployeeExample);

        orderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void transOrder(Integer orderId, String state) throws ServiceException {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new ServiceException("操作异常!");
        }
        if (order.getState().equals(state)) {
            throw new ServiceException("操作异常!");
        }

        // 设置订单状态为已下发
        order.setState(state);
        orderMapper.updateByPrimaryKeySelective(order);
    }


    /**
     * 新增配件订单关系表
     * @param OrderId 订单id
     * @param partsVoList 零件列表
     */
    private void addOrderParts(Integer OrderId, List<PartsVo> partsVoList) {
        for(PartsVo partsVo : partsVoList ){
            OrderParts orderParts = new OrderParts();
            orderParts.setOrderId(OrderId);
            orderParts.setPartsId(partsVo.getId());
            orderParts.setNum(partsVo.getNum());
            orderPartsMapper.insertSelective(orderParts);
        }

    }

    /**
     * 新增员工订单关系表
     * @param orderId 订单id
     * @param employeeId 员工id
     */
    private void saveEmployeeOrder(Integer orderId, Integer employeeId) {

        OrderEmployee orderEmployee = new OrderEmployee();
        orderEmployee.setOrderId(orderId);
        orderEmployee.setEmployeeId(employeeId);
        orderEmployeeMapper.insertSelective(orderEmployee);
    }
}
